﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using MP3ToAudioBookWithChapters.WinForms.Properties;
using MP3ToAudioBookWithChapters.Library;
using System.Threading;
using System.Diagnostics;

namespace MP3ToAudioBookWithChapters.WinForms
{
    public partial class MainForm : Form
    {
        AudiobookManager manager;
        BackgroundThread backgroundWorker;

        public MainForm()
        {
            InitializeComponent();
            statusLabel.Text = "Ready";

            backgroundWorker = new BackgroundThread();
            Controls.Add(backgroundWorker);


            EnsureLameExists();
            EnsureNeroAacEncExists();
            EnsureMp4ChapsExists();
        }

        private void SelectFolder(string folderPath)
        {
            manager = new AudiobookManager(folderPath);
            if (manager.Chapters.Count > 0)
            {

                this.selectedPath.Text = manager.ChapterPath;
                this.targetFileName.Text = manager.AudiobookFileName;

                chapterList.Items.Clear();
                foreach (var chapter in manager.Chapters)
                {
                    var lvi = new ListViewItem(chapter.DisplayName);
                    lvi.Tag = chapter;
                    chapterList.Items.Add(lvi);
                }
                
                Settings.Default.PreviousPath = folderPath;
                Settings.Default.Save();
            }
            else
            {
                manager = null;
            }
        }

        private void EnableButtons(bool enabled)
        {
            generate.Enabled = enabled;
            selectFolder.Enabled = enabled;
        }

        private void Generate()
        {
            EnableButtons(false);
            backgroundWorker.Initialize(manager.Generate);
            
            manager.ProgressUpdated += backgroundWorker.UpdateProgress;
            manager.LogUpdated += backgroundWorker.UpdateLog;
            manager.GenerateCancelled += backgroundWorker.Cancel;

            backgroundWorker.WorkEnded += GenerateCompleted;
            backgroundWorker.WorkProgressUpdated += GenerateProgressChanged;
            backgroundWorker.WorkLogUpdated += GenerateLogChanged;
            backgroundWorker.WorkCancelled += GenerateCancelled;

            backgroundWorker.Begin();
        }

        private void GenerateCancelled()
        {
            EnableButtons(true);
        }

        private void GenerateCompleted()
        {
            EnableButtons(true);
        }

        private void GenerateProgressChanged(int percentComplete)
        {
            progress.Value = percentComplete;
        }

        private void GenerateLogChanged(string message, params string[] args)
        {
            if (args != null && args.Length > 0)
                statusLabel.Text = string.Format(message, args);
            else
                statusLabel.Text = message;
        }


        //-------------------------------------------------


        private void MainForm_Load(object sender, EventArgs e)
        {
            if (Settings.Default.PreviousPath == null ||
                !Directory.Exists(Settings.Default.PreviousPath))
            {
                Settings.Default.PreviousPath = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
                Settings.Default.Save();
            }
            else
            {
                SelectFolder(Settings.Default.PreviousPath);
            }

        }


        private void exit_Click(object sender, EventArgs e)
        {
            Application.Exit();
        }

        private void generate_Click(object sender, EventArgs e)
        {
            Generate();
        }

        private void EnsureMp4ChapsExists()
        {
             if (!File.Exists(Library.Properties.Settings.Default.NeroEncoderPath))
             {
                 MessageBox.Show(this,
                     "Cannot find MP4 Tools Chapter Converter, please click OK and navigate to mp4chaps.exe",
                     "Cannot find dependency", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);

                openFileDialog.Title = "Cannot find MP4 Tools Chapter Converter, please navigate to mp4chaps.exe";
                var result = openFileDialog.ShowDialog(this);
                if (result == DialogResult.OK)
                {
                    Library.Properties.Settings.Default.Mp4ChapsPath = openFileDialog.FileName;
                    Library.Properties.Settings.Default.Save();
                }
                else
                {
                    Process.Start("http://kurtnoise.free.fr/mp4tools/mpeg4ip-1.6.1_20071130.zip");
                    Application.Exit();
                }
            }
            
        }

        private void EnsureNeroAacEncExists()
        {
            if (!File.Exists(Library.Properties.Settings.Default.NeroEncoderPath))
            {
                MessageBox.Show(this,
                    "Cannot find Nero Aac Encoder, please click OK and navigate to NeroAacEnc.exe",
                    "Cannot find dependency", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);


                openFileDialog.Title = "Cannot find Nero Aac Encoder, please navigate to NeroAacEnc.exe";
                var result = openFileDialog.ShowDialog(this);
                if (result == DialogResult.OK)
                {
                    Library.Properties.Settings.Default.NeroEncoderPath = openFileDialog.FileName;
                    Library.Properties.Settings.Default.Save();
                }
                else
                {
                    Process.Start("http://www.nero.com/eng/downloads-nerodigital-nero-aac-codec.php");
                    Application.Exit();
                }
            }
        }

        private void EnsureLameExists()
        {
            if (!File.Exists(Library.Properties.Settings.Default.LamePath))
            {
                MessageBox.Show(this, 
                    "Cannot find Lame, please click OK and navigate to lame.exe", 
                    "Cannot find dependency", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);

                openFileDialog.Title = "Cannot find Lame, please navigate to lame.exe";
                var result = openFileDialog.ShowDialog(this);
                if (result == DialogResult.OK)
                {
                    Library.Properties.Settings.Default.LamePath = openFileDialog.FileName;
                    Library.Properties.Settings.Default.Save();
                }
                else
                {
                    Process.Start("http://www.rarewares.org/dancer/dancer.php?f=226");
                    Application.Exit();
                }
            }
        }


        private void selectFolder_Click(object sender, EventArgs e)
        {
            if (Settings.Default.PreviousPath != null &&
                Directory.Exists(Settings.Default.PreviousPath))
                folderBrowserDialog.SelectedPath = Settings.Default.PreviousPath;

            var result = folderBrowserDialog.ShowDialog(this);
            if (result == DialogResult.OK)
            {
                SelectFolder(folderBrowserDialog.SelectedPath);
            }
        }


        private void moveUp_Click(object sender, EventArgs e)
        {
            foreach (var item in chapterList.SelectedItems)
            {

            }
        }

        private void moveDown_Click(object sender, EventArgs e)
        {
            foreach (var item in chapterList.SelectedItems)
            {

            }
        }

        private void MainForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            backgroundWorker.Cancel();
        }

    }
}
